import { FC, useMemo, useRef, useEffect } from 'react';
import { RouteComponentProps } from 'react-router'
import _ from 'lodash';
import moment from 'moment';
import { message, Modal, notification } from 'antd';
import { WithNormalRender } from "@ey-render/hoc-form";
import { getSubmitFormValues, getFormValues } from '@ey-utils/utils/formily-utils/getSubmitFormValues';
import { history } from 'umi';
import { uuidv4 } from '@/utils/utils';
import { onFieldChange, onFieldInit, onFieldMount, onFieldValueChange, onFormMount } from '@formily/core';
import api, { archivesBoxUpdate, numberPage, archivesPageByBox } from './services';
import { Form } from '@formily/core/esm/models';
import {useParams} from "react-router-dom";
import components from "@/components/schema-form-render/schema-components-registed/components-biz";

interface FileBoxEditProps extends RouteComponentProps {}

const FileBoxEdit: FC<FileBoxEditProps> = ({

}) => {
    const { id } = useParams();
  const billCodeRef = useRef<any>();
  const modalRef = useRef<any>();

  useEffect(() => {
    document.addEventListener('keydown', (e) => {
      if (e.code === 'Enter') {
        modalRef.current?.destroy?.();
      }
    })
  }, [])

  const detailApi: any = useMemo(() => {
    return {
        remoteUrl: api.detail,
        method: 'POST',
        remoteParams: {
          id,
        },
        pageCode: 'ArcvFileBox_U',
    };
  }, [id]);
  const handleBack = () => {
    return history.back();
  };

  const BillFormLayout = useMemo(() => {
    return WithNormalRender({
        filedConfig: {},
        components: {
            ...components,
        },
    });
  }, []);

  // 提交
  const submit = async ({ form }: any) => {
    const formValues = await getSubmitFormValues(form);
    if (formValues) {
      const params = {
        ...formValues,
        id,
        pageCode: 'ArcvFileBox_U'
      };
      const res: any = await archivesBoxUpdate(params);

      const { success } = res || {};

      if (success) {
        handleBack();
      }

      return res;
    }

    return {
      success: false,
    };
  };

  const searchArchives = _.debounce(async (form: Form<any>, code: string) => {
    const { arcvItems, coCode, yearMonth } = form.values;

    if (!coCode) {
      message.error('请先选择归档公司');
      return;
    }

    if (!yearMonth) {
      message.error('请选择所属会计期间');
      return;
    }

    const res: any = await archivesPageByBox({
      pageNo: 1,
      pageSize: 20,
      queryKeys: {
        bizCode: code,
        qzCode: coCode,
        yearMonth,
        pageCode: 'ArcvManage_Items_L',
      },
    });

    if (res.success) {
      if (!res.result?.content?.length) {
        modalRef.current = Modal.confirm({
          title: `单据号 ${code} 对应的案件未达到归档状态`,
          cancelButtonProps: {style: { display: 'none' }},
          onOk: () => {
            form.setFieldState('billCode', (field: any) => {
              field.value = '';
              billCodeRef.current?.focus();
            })
          }
        })

        return;
      }

      let newArcvItems: any[] = [...arcvItems];
      let repeatArcvCodes: any[] = [];

      res.result.content.forEach((item: any) => {
        if (arcvItems.find((o: any) => item.code === o.code)) {
          repeatArcvCodes.push(item.code);
          return;
        }
        newArcvItems = [item, ...newArcvItems];
      })
      form.setValuesIn('arcvItems', newArcvItems);

      if (repeatArcvCodes.length > 0) {
        notification.warning({
          message: `案件业务单号 ${code} 下存在重复的案件`,
          duration: 5
        });
      }
    }
    form.setValuesIn('billCode', undefined);
  }, 500);

  const setArcvItemsProps = (form) => {
      form.setFieldState('arcvItems', (state: any) => {
          state.componentProps = {
              ...state.componentProps,
              extraPrams: {
                  arcvStatus: "Archived",
                  qzCode: form.values.coCode,
                  yearMonth: form.values.yearMonth
              },
          }
      })
  }

  return (
    <BillFormLayout
      anchor
      type="NORMAL"
      {...detailApi}
      events={{
        submit,
      }}
      formConfigs={{
        effects: () => {
            onFieldInit('billCode', (field: any, form) => {
              field.componentProps.onInput = async (e: any) => {
                const code = e.target.value;

                searchArchives(form, code);
              };
              field.componentProps.ref = billCodeRef;
            });
            onFieldMount('arcvItems', (field, form) => {
              field.componentProps = {
                ...field.componentProps,
                extraPrams: {
                  status: "Archived",
                    qzCode: form.values.coCode,
                  yearMonth: form.values.yearMonth
                },
                checkClickFn: () => {
                  if (!form.values?.company) {
                    message.error('请先选择归档公司');
                    return false;
                  }
                  return true;
                }
              }
            })
            onFieldChange('belongCo', (field: any, form) => {
                form.setFieldState('whseCode', st => {
                  st.componentProps = _.merge(st.componentProps, {
                    disabled: !field.value,
                    api: {
                      params: {
                        queryKeys: {
                            belongCo: field.value,
                            pageCode: 'ArcvWhse_L'
                        }
                      }
                    }
                  })
                })
                form.setFieldState('cbntCode', st => {
                    st.componentProps = _.merge(st.componentProps, {
                        disabled: !form.values.whseCode,
                        api: {
                            params: {
                                queryKeys: {
                                    belongCo: field.value,
                                    whseCode: form.values.whseCode
                                }
                            }
                        }
                    })
                })

                if (!field.modified) return;

                const { billCode } = form.values;

                !!billCode && searchArchives(form, billCode);
                form.setFieldState('whseCode', state => {
                    state.onInput(undefined)
                });
                form.setValuesIn('cbntCode', undefined);
                form.setValuesIn('whseCodeName', undefined);
                form.setValuesIn('belongCoName', field.inputValues?.[1]?.name);

            })
            onFieldChange('whseCode', (field: any, form) => {
                console.log('###whseCode', field.modified)
                if (!field.modified) return;
                form.setFieldState('cbntCode', st => {
                    st.value = undefined
                    st.componentProps = _.merge(st.componentProps, {
                        disabled: !field.value,
                        api: {
                            params: {
                                queryKeys: {
                                    whseCode: field.value
                                }
                            }
                        }
                    })
                })
                form.setValuesIn('cbntCode', undefined);
            })
            onFieldValueChange('arcvType', (field, form) => {
                if (!field.modified) return;
                form.setValuesIn('protctYears', field.inputValues?.[1]?.triggerNode.props.protctYears);
                form.setValuesIn('arcvTypeName', field.inputValues?.[2]?.[0]);
            })
            onFieldValueChange('coCode', async (field, form) => {
                if (!field.modified) return;
                form.setValuesIn('coName', field.inputValues?.[1]?.name);

                const res: any = await numberPage({
                    pageNo: 1,
                    pageSize: 1,
                    queryKeys: {
                        company: field.value,
                        pageCode: 'ArcvNumber_L'
                    }
                })
                const content = res.result?.content || [];

                // form.setValuesIn('qzCode', content[0]?.code);
                setArcvItemsProps(form)
            })

            onFieldValueChange('yearMonth', (field, form) => {
                setArcvItemsProps(form)
            })
        },
      }}
      filedConfig={{}}
    />
  );
};

export default FileBoxEdit;
